package com.yulongtian.interviewWorks.day20220824;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author YulongTian
 * @date 2022/8/24 - 16:36
 */
public class InterviewsWork07 {

    public static void main(String[] args) {
        ListNode head1 = new ListNode(1);
        ListNode head2 = new ListNode(4);
        head1.next = head2;
        ListNode head3 = new ListNode(3);
        head2.next = head3;
        ListNode head4 = new ListNode(2);
        head3.next = head4;
        ListNode head5 = new ListNode(5);
        head4.next = head5;
        ListNode head6 = new ListNode(2);
        head5.next = head6;

        printList(head1);

        printList(partition(head1, 3));

    }

    public static void printList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + "-");
            head = head.next;
        }
        System.out.println();
    }

    public static ListNode partition(ListNode head, int x) {
        List<Integer> list = new LinkedList<>();
        ListNode p = head;
        while (p != null) {
            list.add(p.val);
            p = p.next;
        }

        boolean flag = false;
        while (!flag) {
            for (int i = 1; i < list.size(); i++) {
                if (list.get(i - 1) > list.get(i)&&list.get(i) >= x) {
                    continue;
                }
                if (list.get(i - 1) > list.get(i)) {
                    swap(list, i - 1, i);
                    flag = true;
                }
            }
            if (flag) {
                flag = false;
            } else {
                break;
            }
        }

        int len = 0;
        p = head;
        while (p != null) {
            p.val = list.get(len++);
            p = p.next;
        }
        return head;
    }

    //交换节点
    public static void swap(List<Integer> list, int i, int j) {
        int temp = list.get(j);
        list.set(j, list.get(i));
        list.set(i, temp);
    }


    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}

